package Experiment5;
import java.util.Stack;
/**
 * Created by Giggle on 2017/6/8.
 */
public class MyDC2 {
    /** constant for addition symbol */
    private final char ADD = '+';
    /** constant for subtraction symbol */
    private final char SUBTRACT = '-';
    /** constant for multiplication symbol */
    private final char MULTIPLY = '*';
    /** constant for division symbol */
    private final char DIVIDE = '/';

    public int value(String postfix){
        Stack<Integer> stack = new Stack();
        int i = 0, result = 0;
        while(i < postfix.length()){
            char ch = postfix.charAt(i);
            if(ch>='0' && ch<='9'){
                result = 0;
                while(ch!=' '){
                    result = result*10 + Integer.parseInt(ch+"");
                    i++;
                    ch = postfix.charAt(i);
                }
                i++;
                stack.push(new Integer(result));
            }
            else{
                int y = stack.pop().intValue();
                int x = stack.pop().intValue();
                switch (ch){
                    case ADD:
                        result = x + y;
                        break;
                    case SUBTRACT:
                        result = x - y;
                        break;
                    case MULTIPLY:
                        result = x * y;
                        break;
                    case DIVIDE:
                        result = x / y;
                }
                stack.push(new Integer(result));
                i++;
            }
        }
        return stack.pop().intValue();
    }
}

